package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
@Transactional
@Slf4j
public class TaskServiceImpl implements TaskService {
    /**
     * 添加延迟任务
     * @param task   任务对象
     * @return
     */
    @Override
    public long addTask(Task task) {
        //1.添加任务到数据库中
        boolean success = addTaskToDb(task);
        if (success){
            //2.添加任务到Redis
            addTaskCache(task);
        }

        return task.getTaskId();
    }

    /**
     * 取消任务
     * @param taskId 任务id
     * @return
     */
    @Override
    public boolean cancelTask(long taskId) {
        boolean flag=false;
        //1.删除任务，更新日志
        Task task = updateDb(taskId,ScheduleConstants.CANCELLED);
        //2.删除redis的数据
        if (task!=null){
            removeTaskFromCache(task);
            flag = true;
        }
        return flag;
    }

    /**
     * 根据类型和优先级拉取任务
     * @param type  类型
     * @param priority  优先级
     * @return
     */
    @Override
    public Task poll(int type, int priority) {
        Task task=null;
        String key= type+"_"+priority;
        try {
            //1.从redis中拉去数据 pop
            String task_json = cacheService.lRightPop(ScheduleConstants.TOPIC + key);
            if (StringUtils.isNotBlank(task_json)){
                task = JSON.parseObject(task_json, Task.class);
                //2.修改数据库信息
                updateDb(task.getTaskId(),ScheduleConstants.EXECUTED);
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error("pull task exception");
        }

        return task;
    }

    /**
     * 删除redis中的数据
     * @param task
     */
    private void removeTaskFromCache(Task task) {
        String key=task.getTaskType()+"_"+task.getPriority();
        if (task.getExecuteTime()<=System.currentTimeMillis()){
            //删除list数据
            cacheService.lRemove(ScheduleConstants.TOPIC+key,0,JSON.toJSONString(task));
        } else {
            cacheService.zRemove(ScheduleConstants.FUTURE+key,JSON.toJSONString(task));
        }
    }

    /**
     * 删除任务，更新任务日志
     * @param taskId
     * @param status
     * @return
     */
    private Task updateDb(long taskId, int status) {
        Task task=null;
        try{
            //根据任务id删除
            taskinfoMapper.deleteById(taskId);
            //更新任务日志
            TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(taskId);
            taskinfoLogs.setStatus(status);
            taskinfoLogsMapper.updateById(taskinfoLogs);
            task=new Task();
            BeanUtils.copyProperties(taskinfoLogs,task);
            task.setExecuteTime(taskinfoLogs.getExecuteTime().getTime());
        }catch (Exception e){
            log.error("task cancel exception taskId={}",taskId);
        }
        return task;
    }

    @Autowired  //redis工具类
    private CacheService cacheService;
    /**
     * 把任务添加到redis中
     * @param task
     */
    private void addTaskCache(Task task) {
        String key=task.getTaskType()+"_"+task.getPriority();
        //获取预设时间--5分钟后的时间 毫秒值
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        long nextScheduleTime = calendar.getTimeInMillis();
        //2.1如果任务执行时间小于等于当前时间，存入list
        if (task.getExecuteTime()<=System.currentTimeMillis()){
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key,JSON.toJSONString(task));

        } else if (task.getExecuteTime()<=nextScheduleTime)
        //2.2如果任务执行时间大于当前时间并且小于等于预设时间（未来5分钟），存入zset
        {
            cacheService.zAdd(ScheduleConstants.FUTURE+key,JSON.toJSONString(task),task.getExecuteTime());
        }

    }

    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    /**
     * 添加任务到数据库中
     * @param task
     * @return
     */
    private boolean addTaskToDb(Task task) {
        boolean flag =false;
        try{
            //保存任务表
            Taskinfo taskinfo=new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);
            //设置taskID
            task.setTaskId(taskinfo.getTaskId());
            //保存任务日志
            TaskinfoLogs taskinfoLogs=new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo,taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            flag=true;
        }catch (Exception e){
            e.printStackTrace();
        }
       return flag;
    }

    /**
     * 未来数据定时刷新  每分钟刷新一次
     * cron  为特有表达式
     */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refresh(){
        //加锁 防止多台定时刷新服务产生 冲突    参数1 锁的名字 参数2 超时时间 单位毫秒
        String token = cacheService.tryLock("FUTRUE_TASK_SYNC", 1000 * 30);
        if (StringUtils.isNotBlank(token)){ //判断是否有锁无锁的情况下才能刷新
            log.info("未来数据定时刷新----定时任务");
            //获取未来说有数据的集合key
            Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            for (String futureKey : futureKeys) {
                //获取当前数据的key  topic
                String topicKey= ScheduleConstants.TOPIC+futureKey.split(ScheduleConstants.FUTURE)[1];
                //按照key和分值查询符合条件的数据
                Set<String> task = cacheService.zRangeByScore(futureKey, 0, System.currentTimeMillis());
                //同步数据
                if(!task.isEmpty()){
                    cacheService.refreshWithPipeline(futureKey,topicKey,task);
                    log.info("成功将"+futureKey+"刷新到了"+topicKey);
                }
            }
        }
    }

    /**
     * 数据库任务定时同步到redis中   每5分钟执行一次
     */
    @PostConstruct  //初始化方法--当微服务启动自动同步
    @Scheduled(cron = "0 */5 * * * ?")
    public void reloadData(){
        //1.清理缓存中的数据    list zset
        clearCache();
        //2.查询符合条件的任务 小于未来5分钟的数据
        Calendar calendar=Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        LambdaQueryWrapper<Taskinfo> wrapper = Wrappers.<Taskinfo>lambdaQuery().lt(Taskinfo::getExecuteTime, calendar.getTime());
        List<Taskinfo> taskinfoList = taskinfoMapper.selectList(wrapper);
        //3.把任务添加到redis
        if (taskinfoList!=null&&taskinfoList.size()>0){
            for (Taskinfo taskinfo : taskinfoList) {
                Task task=new Task();
                BeanUtils.copyProperties(taskinfo,task);
                task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                addTaskCache(task);
            }
        }

        log.info("数据库的任务已同步到redis");
    }

    /**
     * 清理缓存中的数据 list zset
     */
    public void clearCache(){
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        cacheService.delete(topicKeys);
        cacheService.delete(futureKeys);
    }
}